<?php
class Stockist extends AppModel {
	var $name = 'Stockist';
    var $validate = array(
        'name' => array(
            'notEmpty' => array(
                'rule' => 'notEmpty',
            )
        )
    );

    public function listing ($params) {
        $page = $params['page'];
        $cond = 's.`name` IS NOT NULL ';

        if ($params['query'] && $params['qtype']) {
            $cond .= 'AND s.`'.$params['qtype'].'` LIKE "%'.$params['query'].'%" ';
        }

        $sql = 'SELECT COUNT(*) AS total FROM `stockists` AS s ' .
               'WHERE '.$cond;
        $ttl = $this->query($sql);

        $total = (count($ttl) == 0) ? 0 : $ttl[0][0]['total'];
        if ($total == 0) {
            return 0;
        }

        $rpp   = isset($params['rp']) ? $params['rp'] : 10;
        $start = (($page-1) * $rpp);
        $sort  = empty($params['sortname']) ? 'id' : $params['sortname'];
        $ord   = (empty($params['sortorder']) || $params['sortorder'] == 'asc') ? 'ASC' : 'DESC';
        $sql   = 'SELECT s.* FROM `stockists` AS s ' .
                 'WHERE '.$cond .
                 'ORDER BY s.`'.$sort.'` '.$ord.' ' .
                 'LIMIT '.$start.', '.$rpp;
        $data = $this->query($sql);
        $rec  = array();

        if (count($data) == 0) {
            return 0;
        }

        foreach ($data as $rs) {
            $id = $rs['s']['id'];

            $actions  = '<div title="'.__('Modify',true).'" class="editRecord" onclick="editRecord('.$id.');"></div>' .
                        '<div title="'.__('Adjust',true).'" class="adjustment" onclick="adjustStock('.$id.');"></div>' .
                        '<div title="'.__('Report',true).'" class="report"></div><div class="clear" style="height:0; padding:0;"></div>';
            $dateJoin = ($rs['s']['date_join']) ? $this->serverToClientTime($rs['s']['date_join'], 'd/m/Y') : '-';
            $deposit  = ($rs['s']['deposit']) ? number_format($rs['s']['deposit'], 2) : '-';
            $created  = $this->serverToClientTime($rs['s']['created'], 'd/m/Y H:i a');
            $modified = $this->serverToClientTime($rs['s']['modified'], 'd/m/Y H:i a');

            $cell = array(
                $rs['s']['id'], $dateJoin, $rs['s']['name'], $rs['s']['mobile'], $rs['s']['tel'], $rs['s']['fax'], $rs['s']['address'],
                $rs['s']['city'], $rs['s']['state'], $rs['s']['country'], $deposit, $rs['s']['bank_account'], $rs['s']['remark'], $modified, $actions
            );

            $rec[] = array(
                'id'   => $id,
                'cell' => $cell
            );
        }

        return array(
            'page'  => $page,
            'total' => $total,
            'rows'  => $rec
        );
    } // listing
} // Stockist
?>